package propcalc_lang.ast;

import java.util.Map;
import java.util.Random;
import java.util.Set;

/** Negación de una proposición.
 *  @author Leonardo Val.
 */
public class Negation extends Proposition {
	public final Proposition operand;
	
	public Negation(Proposition operand) {
		this.operand = operand;
	}

	@Override public String unparse() {
		return "(! "+ operand.unparse() +")";
	}

	public static Negation generate(Random random, int min, int max) {
		return new Negation(Proposition.generate(random, min-1, max-1));
	}
	
	@Override public Set<String> variables(Set<String> vars) {
		this.operand.variables(vars);		
		return vars;
	}
	
	@Override public Proposition substitution(Map<String, Proposition> replacements) {
		return new Negation(operand.substitution(replacements)); 
	}
	
	@Override public boolean match(Proposition pattern, Map<String, Proposition> replacements) {
		if (pattern instanceof Variable) {
			Variable var = (Variable) pattern;
			if (replacements.containsKey(var.identifier)) {
				return this.equals(replacements.get(var.identifier));
			} else {
				replacements.put(var.identifier, this);
				return true;
			}
		} else {
			if (pattern instanceof Negation) {
				Negation bic = (Negation) pattern;
				return this.operand.match(bic.operand, replacements);
			}
		}
		return false;
	}
	
	@Override public String toString() {
		return "Negation("+ operand +")";
	}

	@Override public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((operand == null) ? 0 : operand.hashCode());
		return result;
	}

	@Override public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Negation other = (Negation) obj;
		if (operand == null) {
			if (other.operand != null)
				return false;
		} else if (!operand.equals(other.operand))
			return false;
		return true;
	}

}
